package com.gitee.form_token.token;

import com.gitee.form_token.common.RedisUtil;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 自定义处理
 * -- 令牌校验
 **/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {

        String path = request.getRequestURI();

        String[] words = {"/", "/home"};
        List<String> whiteList = Arrays.asList(words);

        if (path.endsWith(".ico") || path.endsWith(".html") || whiteList.contains(path)) {
            filterChain.doFilter(request, response);
            return;
        }

        if (path.startsWith("/assets") || path.startsWith("/auth") || path.startsWith("/app")) {
            filterChain.doFilter(request, response);
            return;
        }

        // Token校验
        String subject = CheckWebToken.getSubject(request);
        String redisKey = "user:" + subject;

        Object userObj = redisUtil.get(redisKey);

        if (userObj == null) {
            throw new BadCredentialsException("redis读取null");
        }

        // 设置到上下文
        UserDetails userDetails = (UserDetails) userObj;
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 过滤放行
        filterChain.doFilter(request, response);
    }
}
